package cn.web.web_module.controller;

import com.alibaba.fastjson.JSONObject;
import com.sun.jndi.toolkit.url.UrlUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.Map;

/**
 * @Author: 张松
 * @Description:
 * @Date: Created in 14:19 2020/11/17
 * @Modified By:
 */

@RestController
@RequestMapping("/user")
public class TestXcx {

    @RequestMapping("/demo")
    public String ceshiUser(){
//        String scene="osdn25dtBEQ_Sx0yrH2dneMg5iFM";
//        String accessToken="39_JqAEXBYU8AJR1jmMsLRLKeWsWQ0p3o76sHyXK-9lA7Reu6H65cDrFbmLP_Cr0H9GSAJRqW8iOeM0n456YLBGCtHTEHjPFmz5iTR2-85HZpiF2j8efGf53gsUbySkKVytzZNFn2mVec5FqA6wIJNbABADEI";
//        String s = postMiniqrQr(scene, accessToken);
        String token = getToken();
        postMiniqrQr("osdn25acH7Rf86i4-pmggP6DCrhU",token);

        return token;
    }


    /**
     * 生成带参小程序二维码
     * @param scene	要输入的内容
     * @param accessToken	token
     */
    String postMiniqrQr(String scene, String accessToken) {
        try{
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true); // 打开写入属性
            httpURLConnection.setDoInput(true); // 打开读取属性
            httpURLConnection.setRequestMethod("POST");// 提交方式
            // 不得不说一下这个提交方式转换！！真的坑。。改了好长时间！！一定要记得加响应头
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");// 设置响应头
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene); // 你要放的内容
            paramJson.put("path", "pages/index/index");
            paramJson.put("width", 430); // 宽度
            paramJson.put("auto_color", true);

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();

            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

            //创建一个空文件
            OutputStream os = new FileOutputStream(new File("D:a/"+scene+".jpg"));

//            OutputStream os = new FileOutputStream(new File("E:\\images\\"+scene+".jpg"));

            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1)
            {
                os.write(arr, 0, len);
                os.flush();
            }

            os.close();

            return "https://www.dhnep.cn:8181/dhn/icon/ewm/"+scene+".jpg";

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "";
    }


    public static String getToken() {
        try {
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("grant_type", "client_credential");
            map.put("appid", "wx51d55df222d9901e");// 改成自己的appid
            map.put("secret", "5f71b93e3a56d190c10c8612fc1eb5fb"); //改成自己的secret
            String rt = sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
            JSONObject json = JSONObject.parseObject(rt);
            if (json.getString("access_token") != null || json.getString("access_token") != "") {
                System.out.println("token:" + json.getString("access_token"));
                return json.getString("access_token");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }
        System.out.println(param);
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
